<?php
declare (strict_types = 1);

namespace App\Models;

/**
 * 轮播图
 * @mixin \think\Model
 */
class BannerModel extends BaseModel
{
    use SoftDeletes;
    protected $table = 'banner';
    //fillable为白名单，表示该字段可被批量赋值；guarded为黑名单，表示该字段不可被批量赋值。
    protected $fillable = ['position','name','picture','url'];
    //如自动写入时间戳但没有创建时间字段情况，设置 CREATED_AT 为空，来限制他的更新
    const CREATED_AT = null;

    /**
     * 位置
     */
    public static function position($position = 0){
        $arr = [
            ['id' => 1, 'name' => '首页'],
        ];
        if($position){
            foreach ($arr as $k => $v) {
                if($v['id'] == $position) $name = $v['name'];
            }
            return $name;
        }
        return $arr;
    }

    /**
     * 轮播图编辑添加
     */
    public static function editBanner($data = [])
    {
        try{
            $id = $data['id'];
            unset($data['id']);
            if(!empty($id)){
                $res = self::where('id',$id)->update($data);
            }else{
                $res = self::create($data);
            }
            if($res) {
                return self::result("", 200, "操作成功");
            }
            return self::result('',500,'操作失败');

        }catch (\Exception $e){
            return self::result('',500,$e->getMessage());
        }
    }

    /**
     * 获取轮播图列表
     */
    public static function getBannerList($pageSize, $page, $map)
    {
        $list = self::select('*')
            ->where($map)
            ->orderBy('sort','asc')
            ->paginate($pageSize,[],'page', $page)->toArray();

        return $list;
    }

    /**
     * banner列表
     * @param integer $position
     * @param integer $limit
     */
    public static function getList($position = 1, $limit = 5)
    {
        $map['position'] = $position;
        $map['is_show'] = 1;
        return self::field('name,picture,url')->where($map)->order('sort asc')->limit($limit)->select()->toArray();
    }

}
